package org.yuangu.privacyfinance.activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.privacy.accountmgr.R;

import org.yuangu.privacyfinance.activities.adapter.AbstractRecyclerViewHolder;
import org.yuangu.privacyfinance.activities.adapter.CategoryWrapper;
import org.yuangu.privacyfinance.activities.adapter.EntityListAdapter;
import org.yuangu.privacyfinance.activities.adapter.OnItemClickListener;
import org.yuangu.privacyfinance.activities.dialog.CategoryDialog;
import org.yuangu.privacyfinance.activities.helper.SwipeController;
import org.yuangu.privacyfinance.activities.viewmodel.BaseViewModel;
import org.yuangu.privacyfinance.activities.viewmodel.CategoriesViewModel;
import org.yuangu.privacyfinance.domain.FinanceDatabase;
import org.yuangu.privacyfinance.domain.model.Category;
import org.yuangu.privacyfinance.helpers.CurrencyHelper;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Activity that shows all categories. Also provides the possibility to create new categories.
 */
public class CategoriesActivity extends BaseActivity implements OnItemClickListener<CategoryWrapper> {
    private CategoriesAdapter categoriesAdapter;
    private RecyclerView recyclerView;
    private TextView emptyView;
    private CategoriesViewModel viewModel;
    private SwipeController swipeController = null;


    @Override
    protected Class<? extends BaseViewModel> getViewModelClass() {
        return CategoriesViewModel.class;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContent(R.layout.content_recycler);

        viewModel = (CategoriesViewModel) super.viewModel;
        categoriesAdapter = new CategoriesAdapter(this, viewModel.getCategories());
        categoriesAdapter.onItemClick(this);

        addFab(R.layout.fab_add, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openCategoryDialog(null);
            }
        });

        recyclerView = findViewById(R.id.recycler_view);
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 1);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(categoriesAdapter);

        emptyView = findViewById(R.id.empty_view);
        emptyView.setText(getString(R.string.activity_categories_empty_list_label));
        viewModel.getCategories().observe(this, new Observer<List<CategoryWrapper>>() {
            @Override
            public void onChanged(@Nullable List<CategoryWrapper> categoryWrappers) {
                if (categoryWrappers.isEmpty()) {
                    recyclerView.setVisibility(View.GONE);
                    emptyView.setVisibility(View.VISIBLE);
                } else {
                    recyclerView.setVisibility(View.VISIBLE);
                    emptyView.setVisibility(View.GONE);
                }
            }
        });

        SwipeController.SwipeControllerAction deleteAction = new SwipeController.SwipeControllerAction() {
            @Override
            public void onClick(int position) {
                deleteCategory(viewModel.getCategories().getValue().get(position).getCategory());
            }

            @Override
            public Drawable getIcon() {
                return ContextCompat.getDrawable(CategoriesActivity.this, R.drawable.ic_delete_red_24dp);
            }
        };

        swipeController = new SwipeController(this, deleteAction, deleteAction);

        ItemTouchHelper itemTouchhelper = new ItemTouchHelper(swipeController);
        itemTouchhelper.attachToRecyclerView(recyclerView);

        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                swipeController.onDraw(c);
            }
        });

    }

    public void deleteCategory(final Category category) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.category_delete_dialog_title);
        builder.setMessage(Html.fromHtml(getResources().getString(R.string.category_delete_question, category.getName())));
        builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                FinanceDatabase.getInstance().categoryDao().deleteAsync(category);
                Toast.makeText(getBaseContext(), R.string.category_deleted, Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private void openCategoryDialog(Category category) {
        Bundle args = new Bundle();
        if (category == null) {
        } else {
            args.putLong(CategoryDialog.EXTRA_CATEGORY_ID, category.getId());
        }

        CategoryDialog categoryDialog = new CategoryDialog();
        categoryDialog.setArguments(args);

        categoryDialog.show(getSupportFragmentManager(), "CategoryDialog");
    }

    @Override
    public void onItemClick(CategoryWrapper item) {
//        Intent intent = new Intent(this, CategoryActivity.class);
//        intent.putExtra(CategoryActivity.EXTRA_CATEGORY_ID, item.getId());
//        startActivity(intent);
        deleteCategory(item.getCategory());
    }

    public class CategoryViewHolder extends AbstractRecyclerViewHolder {
        private TextView textViewName;
        private TextView textViewBalance;
        private TextView textViewBudget;
        private TextView textViewBudgetLabel;
        private TextView textViewBudgetLeft;
        private ImageView ivCategory;
        private Long budget;

        public CategoryViewHolder(@NonNull View itemView, Context context) {
            super(itemView, context);
            textViewName = itemView.findViewById(R.id.textView_category_name);
            textViewBalance = itemView.findViewById(R.id.textView_balance);
            textViewBudget = itemView.findViewById(R.id.textView_budget);
            textViewBudgetLabel = itemView.findViewById(R.id.textView_budget_label);
            textViewBudgetLeft = itemView.findViewById(R.id.textView_budget_left);
            ivCategory = itemView.findViewById(R.id.imageView_category_icon);
        }

        public void setCategoryName(String name) {
            textViewName.setText(name);
        }

        public void setBalance(Long balance) {
            CurrencyHelper.setBalance(balance, textViewBalance);
            if (budget != null && balance != null) {
                CurrencyHelper.setBalance(budget + balance, textViewBudgetLeft);
                textViewBudgetLeft.setVisibility(View.VISIBLE);
            } else {
                textViewBudgetLeft.setVisibility(View.INVISIBLE);
            }
        }

        public void setBudget(Long budget) {
            this.budget = budget;
            if (budget == null) {
                textViewBudget.setVisibility(View.INVISIBLE);
                textViewBudgetLabel.setVisibility(View.INVISIBLE);
                textViewBudgetLeft.setVisibility(View.INVISIBLE);
            } else {
                textViewBudget.setVisibility(View.VISIBLE);
                textViewBudgetLabel.setVisibility(View.VISIBLE);

            }
            CurrencyHelper.setBalance(budget, textViewBudget, false);
        }

        public void setCategoryColor(Integer color) {
            if (color != null) {
                ivCategory.setColorFilter(color);
            } else {
                ivCategory.clearColorFilter();
            }
        }
    }

    public class CategoriesAdapter extends EntityListAdapter<CategoryWrapper, CategoryViewHolder> {
        public CategoriesAdapter(BaseActivity context, LiveData<List<CategoryWrapper>> data) {
            super(context, data);
        }

        @NonNull
        @Override
        public CategoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View viewItem = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.card_category, parent, false);
            return new CategoryViewHolder(viewItem, context);
        }

        @Override
        public void onBindViewHolder(@NonNull final CategoryViewHolder holder, int index) {
            super.onBindViewHolder(holder, index);
            Category category = getItem(index).getCategory();
            holder.setCategoryName(category.getName());
            holder.setCategoryColor(category.getColor());
            holder.setBudget(getItem(index).getCategory().getBudget());
            getItem(index).getBalance().observe(context, new Observer<Long>() {
                @Override
                public void onChanged(@Nullable Long balance) {
                    holder.setBalance(balance);
                }
            });
        }
    }
}
